import { _decorator } from 'cc';
import { WECHAT } from 'cc/env';
import { Global } from '../Global';

const { ccclass } = _decorator;

@ccclass('WxPlatform')
export class WxPlatform {
    static _ins: WxPlatform;
    public wx = window['wx'];

    static get ins() {
        if (!this._ins) {
            this._ins = new WxPlatform();
        }
        return this._ins;
    }

    /** 微信初始化设置（分享菜单 + 热更新） */
    wechat_setting() {
        if (!WECHAT) return;

        const wx = this.wx;

        wx.showShareMenu({
            withShareTicket: true,
            menus: ['shareAppMessage', 'shareTimeline'],
        });

        const updateManager = wx.getUpdateManager();

        updateManager.onCheckForUpdate(res => {
            console.log('请求完新版本信息的回调', res.hasUpdate);
        });

        updateManager.onUpdateReady(() => {
            wx.showModal({
                title: '更新提示',
                content: '新版本已经准备好，是否重启应用？',
                success(res) {
                    if (res.confirm) {
                        updateManager.applyUpdate();
                    }
                },
            });
        });

        updateManager.onUpdateFailed(() => {
            console.log('新版本下载失败');
        });
    }

    /** 显示插屏广告，可延迟秒数后展示 */
    show_interstitial(delay = 0) {
        console.log('显示插屏广告》》》》》》》》');
        if (!WECHAT) return;

        const wx = this.wx;
        const adId = Global.ad_intersitial_id.trim();
        const interstitialAd = wx.createInterstitialAd({ adUnitId: adId });

        interstitialAd?.load().then(() => {
            console.log('插屏广告加载成功');
        });

        interstitialAd?.onClose(res => {
            console.log('关闭插屏广告', res);
        });

        interstitialAd?.onError(err => {
            console.log('插屏广告加载失败', err);
        });

        setTimeout(() => {
            interstitialAd?.show().catch(err => {
                console.log('插屏广告展示失败', err);
            });
        }, delay * 1000);
    }

    rewardVideo: any;

    /** 显示激励视频广告 */
    show_reward_video(callback: Function) {
        if (!WECHAT) return;

        const wx = this.wx;
        const adId = Global.ad_video_id.trim();

        const rewardedVideoAd = wx.createRewardedVideoAd({ adUnitId: adId });

        if (this.rewardVideo) {
            this.rewardVideo.offClose(this._rewardCloseHandler);
        }

        this.rewardVideo = rewardedVideoAd;

        rewardedVideoAd.load().then(() => {
            console.log('激励视频广告加载成功');

            wx.showToast({
                title: '看完视频领奖励',
                icon: 'success',
                duration: 1500,
            });

            rewardedVideoAd.show();
        });

        rewardedVideoAd.onError(err => {
            console.log('激励视频广告加载失败', err);
            wx.showToast({
                title: '请稍后再试',
                icon: 'none',
                duration: 1500,
            });
            callback(2);
        });

        // 定义和绑定关闭事件
        this._rewardCloseHandler = function (res) {
            if (res?.isEnded) {
                callback(1);
            } else {
                console.log('视频未完整观看');
                callback(0);
            }
            rewardedVideoAd.offClose(this._rewardCloseHandler);
        }.bind(this);

        rewardedVideoAd.onClose(this._rewardCloseHandler);
    }

    private _rewardCloseHandler: Function;

    banner: any;
    banner_show_status: boolean = false;

    /** 显示 Banner 广告 */
    show_banner(style = 2) {
        if (!WECHAT) return;

        const wx = this.wx;

        if (this.banner) {
            this.banner.destroy();
            this.banner = null;
        }

        this.banner_show_status = true;

        const adId = Global.ad_banner_id;
        const winSize = wx.getSystemInfoSync();

        const bannerAd = wx.createBannerAd({
            adUnitId: adId,
            adIntervals: 30,
            style: { left: 0, top: 500, width: 300 },
        });

        const computeLeft = () => {
            if (style === 1) return winSize.windowWidth - bannerAd.style.realWidth;
            if (style === 2) return winSize.windowWidth / 2 - bannerAd.style.realWidth / 2;
            return 0;
        };

        bannerAd.onResize(() => {
            bannerAd.style.top = winSize.windowHeight - bannerAd.style.realHeight;
            bannerAd.style.left = computeLeft();
        });

        bannerAd.onLoad(() => {
            console.log('banner 广告加载成功');
            this.banner = bannerAd;

            if (!this.banner_show_status) {
                this.hide_banner();
                console.log('错误触发，关闭 banner');
            }
        });

        bannerAd.onError(err => {
            console.log('banner 广告加载失败', err);
        });

        bannerAd.show();
    }

    /** 隐藏 Banner 广告 */
    hide_banner() {
        this.banner_show_status = false;
        if (this.banner) {
            this.banner.destroy();
            this.banner = null;
            console.log('关闭 banner...');
        }
    }

    isWechatGame() {
        const wx = this.wx;
        return WECHAT && typeof wx !== 'undefined' && !!wx.login;
    }
}
